package com.qqtech.qquan.pub.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.BizzLevel1Enum;
import com.qqtech.core.common.enums.BizzLevel2Enum;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.activity.model.ActivityBaseVo;
import com.qqtech.qquan.activity.service.ActivityBaseService;
import com.qqtech.qquan.circle.model.CircleTopic;
import com.qqtech.qquan.circle.service.CircleMemberService;
import com.qqtech.qquan.circle.service.CircleTopicService;
import com.qqtech.qquan.community.model.CommunityMessage;
import com.qqtech.qquan.community.service.CommunityMessageService;
import com.qqtech.qquan.pub.enums.PubCommentStatusDictEnum;
import com.qqtech.qquan.pub.model.PubComment;
import com.qqtech.qquan.pub.model.PubCommentQuery;
import com.qqtech.qquan.pub.model.PubCommentVo;
import com.qqtech.qquan.pub.service.PubCommentService;
import com.qqtech.qquan.push.service.PushBizzService;
import com.qqtech.qquan.sys.enums.SysConst;
import com.qqtech.qquan.user.model.UserBase;
import com.qqtech.qquan.user.model.UserBaseVo;
import com.qqtech.qquan.user.model.UserTopic;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.qquan.user.service.UserTopicService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/pub/comment")
public class PubCommentController extends BaseWebController<PubComment, PubCommentQuery> {
	@Resource
	private PubCommentService pubCommentService;

	@Resource
	private UserBaseService userBaseService;

	@Resource
	private CircleTopicService circleTopicService;
	@Resource
	private CircleMemberService circleMemberService;
	@Resource
	private UserTopicService userTopicService;

	@Resource
	private CommunityMessageService communityMessageService;
	@Resource
	private PushBizzService pushBizzService;

	@Resource
	private ActivityBaseService activityBaseService;

	@Override
	protected BaseService<PubComment> getBaseService() {
		return pubCommentService;
	}

	/**
	 * 评论列表
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public Result list(@RequestBody PubCommentQuery pubCommentQuery) {
		Result result = new Result();
		pubCommentQuery.setStatus(PubCommentStatusDictEnum.NORMAL.getCode());
		Pageable pageKit = new PageKit(pubCommentQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<PubCommentVo> commentPage = pubCommentService.queryPageList(pubCommentQuery, pageKit);
		List<PubCommentVo> commentList = commentPage.getContent();
		PubCommentVo pubCommentVo2 = null;
		UserBaseVo beCommentUser = null;
		UserBaseVo userVo = null;// 评论人
		if (commentList != null && commentList.size() > 0) {
			for (PubCommentVo pubCommentVo : commentList) {
				userVo = userBaseService.getById(pubCommentVo.getCreatorId());
				if (userVo != null) {
					pubCommentVo.setCreatorImg(userVo.getFullLogo());
					pubCommentVo.setCreatorName(userVo.getNick());
				} else {
					pubCommentVo.setCreatorName("未知用户");
				}
				pubCommentVo.setBeCommented(false);
				pubCommentVo.setBeCommentedName("");
				if (pubCommentVo.getBeCommentedId() != null && pubCommentVo.getBeUserId() != null) {
					pubCommentVo2 = pubCommentService.getById(pubCommentVo.getBeCommentedId());
					beCommentUser = userBaseService.getById(pubCommentVo2.getCreatorId());
					pubCommentVo.setBeCommentedName(beCommentUser.getNick());
					pubCommentVo.setBeCommented(true);

				}
			}
		}

		result.put("commentPage", commentPage);
		return result;
	}

	/**
	 * 分页
	 * 
	 * @param pubCommentQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/manage/page")
	@ResponseBody
	public Result managePage(@RequestBody PubCommentQuery pubCommentQuery) {
		Result result = new Result();
		UserBaseVo userVo = null;
		Integer curUserId = super.getUserId();
		pubCommentQuery.setCreatorId(curUserId);
		pubCommentQuery.setStatus(PubCommentStatusDictEnum.NORMAL.getCode());
		Pageable pageKit = new PageKit(pubCommentQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<PubCommentVo> page = pubCommentService.queryPageList(pubCommentQuery, pageKit);
		List<PubCommentVo> commentList = page.getContent();
		if (commentList != null && commentList.size() > 0) {
			for (PubCommentVo praise : page.getContent()) {
				if (BizzLevel2Enum.CIRCLE_TOPIC.getCode().equals(praise.getBizzType())) {
					CircleTopic topic = circleTopicService.getById(praise.getBizzId());
					if (topic != null) {
						praise.setBizzTitle(topic.getContent());
						praise.setBizzImg(topic.getImg());
					}
				} else if (BizzLevel2Enum.COMMUNITY_MESSAGE.getCode().equals(praise.getBizzType())) {
					CommunityMessage msg = communityMessageService.getById(praise.getBizzId());
					if (msg != null) {
						praise.setBizzTitle(msg.getContent());
						praise.setBizzImg(msg.getImg());
					}
				} else if (BizzLevel2Enum.USER_TOPIC.getCode().equals(praise.getBizzType())) {
					UserTopic userTopic = userTopicService.getById(praise.getBizzId());
					if (userTopic != null) {
						praise.setBizzTitle(userTopic.getContent());
						praise.setBizzImg(userTopic.getImg());
					}
				} else if (BizzLevel1Enum.ACTIVITY.getCode().equals(praise.getBizzType())) {
					ActivityBaseVo activityBaseVo = activityBaseService.getById(praise.getBizzId());
					if (activityBaseVo != null) {
						praise.setBizzTitle(activityBaseVo.getName());
						praise.setBizzImg(activityBaseVo.getLogo());
					}
				}
				praise.setImgString(praise.getBizzImg(), SysConst.IMG_POSTFIX);
				if (praise.getBeUserId() != null) {
					userVo = userBaseService.getById(praise.getBeUserId());
					if (userVo != null) {
						praise.setBeUserImg(userVo.getLogo());
						praise.setBeUserName(userVo.getNick());
					}
				}
			}
		}
		result.put("page", page);
		return result;
	}

	/**
	 * 发表评论
	 * 
	 * @param pubComment
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/doAdd")
	@ResponseBody
	public Result doAdd(@RequestBody PubCommentQuery pubComment) {
		Result ret = new Result();
		if (pubComment == null) {
			ret.addErr("参数不能为空");
		} else {
			if (StringUtil.isBlank(pubComment.getContent())) {
				ret.addErr("评论内容不能为空");
			}
			if (StringUtil.isBlank(pubComment.getBizzType())) {
				ret.addErr("请指定评论业务类型");
			}
			if (pubComment.getBizzId() == null) {
				ret.addErr("请指定评论业务Id");
			}
		}
		if (pubComment.getBizzType().equalsIgnoreCase(BizzLevel2Enum.CIRCLE_TOPIC.getCode())) {
			// 如果是圈子话题，要判断该用户是否圈子的成员
			CircleTopic circleTopic = circleTopicService.getById(pubComment.getBizzId());
			if (circleTopic != null && circleTopic.getCircleId() != null) {
				if (!circleMemberService.isCircleMember(getUserId(), circleTopic.getCircleId())) {
					ret.addErr("你不是圈子成员!");
					return ret;
				}
			} else {
				ret.addErr("找不到该圈子话题!");
				return ret;
			}
		}
		if (pubComment.getBizzType().equalsIgnoreCase(BizzLevel2Enum.COMMUNITY_MESSAGE.getCode())) {
			if (pubComment.getCommunityId() != null) {
				UserBase userBase = userBaseService.getById(super.getUserId());
				if (userBase != null) {
					if (userBase.getCommunityId() == null
							|| pubComment.getCommunityId().intValue() != userBase.getCommunityId().intValue()) {
						ret.addErr("请加入该社区后再给邻里评论");
						return ret;
					}
				}
			}
		}
		if (ret.checkForm()) {
			pubComment.setCreatorId(super.getUserId());
			pubComment.setStatus(PubCommentStatusDictEnum.NORMAL.getCode());
			pubComment.setContent(pubComment.getContent().trim());
			pubCommentService.handleAdd(pubComment);

			// 返回所有评论信息，可用于页面局部刷新评论信息
			List<PubCommentVo> commentList = pubCommentService.queryCommentListByBizz(pubComment.getBizzId(),
					pubComment.getBizzType());
			if (pubComment.getBizzType().equalsIgnoreCase(BizzLevel2Enum.USER_TOPIC.getCode())) {
				userTopicService.increaseComment(pubComment.getBizzId(), 1);// 友事评论数量+1
				if (commentList != null && commentList.size() > 0) {
					for (PubCommentVo pubCommentVo : commentList) {
						UserBaseVo user = userBaseService.getById(pubCommentVo.getCreatorId());
						pubCommentVo.setCreatorImg(user.getLogo());
						pubCommentVo.setCreatorName(user.getNick());
						pubCommentVo.setBeCommented(false);
						pubCommentVo.setBeCommentedName("");
						if (pubCommentVo.getBeCommentedId() != null) {
							PubCommentVo beCommentVo = pubCommentService.getById(pubCommentVo.getBeCommentedId());
							if (beCommentVo != null) {
								UserBaseVo beCommentUser = userBaseService.getById(beCommentVo.getCreatorId());
								pubCommentVo.setBeCommentedName(beCommentUser.getNick());
								pubCommentVo.setBeCommented(true);
							}
						}
					}
				}
			}

			ret.put("commentList", commentList);
		}
		return ret;
	}

	/**
	 * 获取评论数
	 * 
	 * @param bizzId
	 * @param bizzType
	 * @return
	 */
	@RequestMapping(value = "/count")
	@ResponseBody
	public Result count(@RequestBody PubComment pubComment) {
		Result ret = new Result();
		int commentCount = pubCommentService.getCommentCountByBizz(pubComment.getBizzId(), pubComment.getBizzType());
		ret.put("commentCount", commentCount);
		return ret;
	}

	/**
	 * 删除评论
	 * 
	 * @param pubComment
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/doDelete")
	@ResponseBody
	public Result doDelete(@RequestBody PubCommentQuery pubComment) {
		Result ret = new Result();
		PubComment tmp = pubCommentService.getById(pubComment.getId());
		if (tmp != null) {
			pubComment.setStatus(PubCommentStatusDictEnum.DELETE.getCode());
			pubCommentService.updateById(pubComment);
			if (tmp.getBizzType().equalsIgnoreCase(BizzLevel2Enum.CIRCLE_TOPIC.getCode())) {
				circleTopicService.increaseComment(tmp.getBizzId(), -1);// 圈子话题评论数量-1
			}
			if (tmp.getBizzType().equalsIgnoreCase(BizzLevel2Enum.USER_TOPIC.getCode())) {
				userTopicService.increaseComment(tmp.getBizzId(), -1);// 友事评论数量-1
			}
			if (tmp.getBizzType().equalsIgnoreCase(BizzLevel2Enum.COMMUNITY_MESSAGE.getCode())) {
				communityMessageService.increaseComment(tmp.getBizzId(), -1);// 社区大喇叭评论数量-1
			}
			// 返回所有评论信息，可用于页面局部刷新评论信息
			List<PubCommentVo> commentList = pubCommentService.queryCommentListByBizz(tmp.getBizzId(),
					tmp.getBizzType());
			ret.put("commentList", commentList);
		}
		return ret;
	}

	/**
	 * 别人对我的评论或回复我的评论
	 * 
	 * @param map
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/manage/comment2me")
	@ResponseBody
	public Result comment2me(@RequestBody Map<String, String> map) {
		Result result = new Result();
		String commentIdsString = map.get("commentIds").toString();// 评论ids
		String[] commentIdsArray = commentIdsString.split(";");
		List<Integer> commentIds = Lists.newArrayList();
		for (int i = 0; i < commentIdsArray.length; i++) {
			if (StringUtil.isNotBlank(commentIdsArray[i])) {
				commentIds.add(Integer.parseInt(commentIdsArray[i]));
			}
		}
		PubCommentQuery pubCommentQuery = new PubCommentQuery();
		pubCommentQuery.setStatus(PubCommentStatusDictEnum.NORMAL.getCode());
		if (commentIds.isEmpty()) {
			commentIds.add(0);
		}
		pubCommentQuery.setIncludeCommentIds(commentIds);
		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.DESC, "id"));
		List<PubCommentVo> commentList = pubCommentService.queryList(pubCommentQuery, pageKit);
		if (commentList != null && commentList.size() > 0) {
			UserBaseVo userVo = null;// 用于取用户呢称、头像
			for (PubCommentVo comment : commentList) {
				userVo = userBaseService.getById(comment.getCreatorId());
				if (userVo != null) {
					comment.setCreatorName(userVo.getNick());
					comment.setCreatorImg(userVo.getLogo());
				}
				if (BizzLevel2Enum.CIRCLE_TOPIC.getCode().equals(comment.getBizzType())) {
					CircleTopic topic = circleTopicService.getById(comment.getBizzId());
					if (topic != null) {
						comment.setBizzTitle(topic.getContent());
						comment.setBizzImg(topic.getImg());
					}
				} else if (BizzLevel2Enum.COMMUNITY_MESSAGE.getCode().equals(comment.getBizzType())) {
					CommunityMessage msg = communityMessageService.getById(comment.getBizzId());
					if (msg != null) {
						comment.setBizzTitle(msg.getContent());
						comment.setBizzImg(msg.getImg());
					}
				} else if (BizzLevel1Enum.ACTIVITY.getCode().equals(comment.getBizzType())) {
					ActivityBaseVo activityBaseVo = activityBaseService.getById(comment.getBizzId());
					if (activityBaseVo != null) {
						comment.setBizzTitle(activityBaseVo.getName());
						comment.setBizzImg(activityBaseVo.getLogo());
					}
				}
				comment.setImgString(comment.getBizzImg(), SysConst.IMG_POSTFIX);
			}
		}
		result.put("commentList", commentList);
		return result;
	}

	/**
	 * 获取评论的业务标题
	 * 
	 * @param comment
	 * @return
	 */
	private String getCommentBizzTitle(PubCommentVo comment) {
		String bizzType = comment.getBizzType();
		if (comment != null) {
			if (bizzType.equalsIgnoreCase(BizzLevel2Enum.CIRCLE_TOPIC.getCode())) {
				CircleTopic topic = circleTopicService.getById(comment.getBizzId());
				return topic != null ? topic.getContent() : "";
			} else if (bizzType.equalsIgnoreCase(BizzLevel2Enum.USER_TOPIC.getCode())) {
				UserTopic topic = userTopicService.getById(comment.getBizzId());
				return topic != null ? topic.getContent() : "";
			} else if (bizzType.equalsIgnoreCase(BizzLevel2Enum.COMMUNITY_MESSAGE.getCode())) {
				CommunityMessage message = communityMessageService.getById(comment.getBizzId());
				return message != null ? message.getContent() : "";
			} else if (bizzType.equalsIgnoreCase(BizzLevel1Enum.ACTIVITY.getCode())) {
				ActivityBaseVo activityBaseVo = activityBaseService.getById(comment.getBizzId());
				return activityBaseVo != null ? activityBaseVo.getName() : "";
			}
		}

		return "";
	}
}
